//
//  XTXVideoPlayViewController.m
//  xiaotianxin
//
//  Created by XYC on 2019/8/18.
//  Copyright © 2019 XYC. All rights reserved.
//

#import "XTXVideoPlayViewController.h"
#import "XTXChatViewController.h"
@interface XTXVideoPlayViewController ()<UIScrollViewDelegate ,UIScrollViewDelegate>{
    MBProgressHUD *progreHud;
    NSString *mp4UrlString;
    AVPlayerLayer * playerLayer;
    AVPlayerItem * playerItem;
    AVPlayer * player;
}
@property (nonatomic, strong) UIImageView *bgImageView01;
@property (nonatomic, strong) UIImageView *bgImageView02;
@property (nonatomic, strong) UIView *bgView01;
@property (nonatomic, strong) UIView *bgView02;
@property (nonatomic ,strong) UIButton *fanhuiBtn;
@property (nonatomic,strong) UIButton *gengduoBtn;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, assign) NSInteger temInter01;
@property (nonatomic, assign) NSInteger temInter02;
@property (nonatomic, assign) BOOL temBol01;
@property (nonatomic, assign) BOOL temBol02;
@property (nonatomic, assign) BOOL temBol03;
@property (nonatomic,strong) UIImageView *bgImageView03;
@property (nonatomic,strong) UIImageView *bgImageView04;
@property (nonatomic, assign) BOOL temBol04;
@property (nonatomic,strong) UIImageView *xqMedoImageViee;
@property(nonatomic, assign) CGFloat pianyiY;
@property(nonatomic, assign) CGFloat tepFlot1;
@property (nonatomic, assign) BOOL temBol05;
@property (nonatomic, strong) NSDictionary *videoDic;
@property (nonatomic ,strong) UIButton *shanliaoBtn;
@end

@implementation XTXVideoPlayViewController

-(UIButton *)shanliaoBtn
{
    if (!_shanliaoBtn) {
        
        _shanliaoBtn = [UIButton new];
        
        [_shanliaoBtn setTitle:@"视频闪聊" forState:UIControlStateNormal];
        
        _shanliaoBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
        
        [_shanliaoBtn setBackgroundImage:[UIImage imageNamed:@"视频闪聊底图"] forState:UIControlStateNormal];
        
        [_shanliaoBtn addTarget:self action:@selector(callButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shanliaoBtn;
}
-(void)callButtonClick{
    [XTXGongTool huoquyonghudegerenxinxiEventClick:self.user_id completionHandler:^(XTXUserModel * _Nonnull model) {
        dispatch_async(dispatch_get_main_queue(), ^{
            XTXChatViewController *msgViewController = [[XTXChatViewController alloc] initWithNibName:NSStringFromClass(XTXChatViewController.class) bundle:nil];
            XTXChatModel *msgmodel = [[XTXChatModel alloc] init];
            msgmodel.user_id = XTXGongTool.share.useMode.id;
            msgmodel.friend_user_id = self.user_id;
            msgmodel.message = @"";
            msgmodel.headimage = model.headimage;
            msgmodel.nickname = model.nickname;
            msgmodel.sex = model.sex;
            msgmodel.goddessflag = model.goddessflag;
            msgViewController.mesageMod = msgmodel;
            [self.navigationController pushViewController:msgViewController animated:YES];
        });
    }];
}
- (NSDictionary *)videoDic
{
    if (!_videoDic) {
        _videoDic = [NSDictionary dictionary];
    }
    return _videoDic;
}

-(UIButton *)fanhuiBtn{
    if (!_fanhuiBtn) {
        _fanhuiBtn = [UIButton new];
        [_fanhuiBtn setImage:[UIImage imageNamed:@"详情-返回"] forState:UIControlStateNormal];
        [_fanhuiBtn addTarget:self action:@selector(backEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    return _fanhuiBtn;
}


-(UIImageView *)bgImageView03{
    if (!_bgImageView03) {
        _bgImageView03 = [UIImageView new];
        _bgImageView03.image = [UIImage imageNamed:@"半透明层"];
    }
    return _bgImageView03;
}

-(UIImageView *)bgImageView04{
    if (!_bgImageView04) {
        _bgImageView04 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, pingmuKuan, pingmuGao)];
        [_bgImageView04 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?x-oss-process=image/resize,w_750",self.datArray[self.medioIdexInte][@"image"]]] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        [_bgImageView04 setContentScaleFactor:[[UIScreen mainScreen] scale]];
        _bgImageView04.contentMode =  UIViewContentModeScaleAspectFill;
        _bgImageView04.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _bgImageView04.clipsToBounds  = YES;
    }
    return _bgImageView04;
}

-(void)zhanshijubao
{
    [XTXGongView.share zhanshijubaohelaheijiemianEventClick:self.datArray[self.medioIdexInte][@"id"] withController:self];
}

-(UIButton *)gengduoBtn{
    if (!_gengduoBtn) {
        _gengduoBtn = [UIButton new];
        [_gengduoBtn setImage:[UIImage imageNamed:@"详情-更多"] forState:UIControlStateNormal];
        [_gengduoBtn addTarget:self action:@selector(zhanshijubao) forControlEvents:UIControlEventTouchUpInside];
    }
    return _gengduoBtn;
}
-(UIImageView *)xqMedoImageViee{
    if (!_xqMedoImageViee) {
        _xqMedoImageViee = [[UIImageView alloc]init];
        _xqMedoImageViee.image = [UIImage imageNamed:@"详情-播放视频"];
    }
    return _xqMedoImageViee;
}

- (NSMutableArray *)datArray
{
    if (!_datArray) {
        _datArray = [NSMutableArray array];
    }
    return _datArray;
}

-(void)huoquyonghuxinxiClick:(NSString *)ID withPush:(BOOL) shifouPush
{
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"id"] = ID;
    WeakSelf
    [XTXNetworking networkingGetUseInfowangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            weakSelf.videoDic = dict[@"info"];
        }
    }];
    
}

-(void)bofangshipingEventClick
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:self.datArray[self.medioIdexInte][@"video"]]) {
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[[NSUserDefaults standardUserDefaults] objectForKey:self.datArray[self.medioIdexInte][@"video"]]];
        [playerLayer removeFromSuperlayer];
        playerItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:fullPath]];
        player = [AVPlayer playerWithPlayerItem:playerItem];
        playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
        playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;
        playerLayer.frame = CGRectMake(0, 0, pingmuKuan, pingmuGao);
        [self.bgView01.layer addSublayer:playerLayer];
        [player play];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(palMedioEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self->player.currentItem];
    }else{
        progreHud = [[MBProgressHUD alloc] init];
        [progreHud hideAnimated:YES];
        [progreHud hideAnimated:YES afterDelay:5.0];
        [self.view insertSubview:progreHud belowSubview:self.fanhuiBtn];
        self.temBol03 = YES;
        [player pause];
        [playerLayer removeFromSuperlayer];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.datArray[self.medioIdexInte][@"video"]]];
        NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {                                                                         dispatch_async(dispatch_get_main_queue(), ^{
            [self->progreHud showAnimated:YES];
            self->progreHud.label.text = [NSString stringWithFormat:@"已加载%.00f％",100.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount];
        });
        }destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->progreHud hideAnimated:YES];
            });
            NSDateFormatter *passionateregistration = [[NSDateFormatter alloc] init];
            [passionateregistration setDateFormat:@"YYYYMMddHHMMssSSS"];
            self->mp4UrlString = [passionateregistration stringFromDate:[NSDate date]];
            NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",self->mp4UrlString]];
            return [NSURL fileURLWithPath:fullPath];
        }completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->progreHud hideAnimated:YES];
            });
            if (!error) {
                [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@.mp4",self->mp4UrlString] forKey:response.URL.absoluteString];
            }
            if (self.temBol03) {
                [self->player pause];
                [self->playerLayer removeFromSuperlayer];
            }
            if ([response.URL.absoluteString isEqualToString:self.datArray[self.medioIdexInte][@"video"]]) {
                self.temBol03 = NO;
                self->playerItem = [AVPlayerItem playerItemWithURL:filePath];
                self->player = [AVPlayer playerWithPlayerItem:self->playerItem];
                self->playerLayer = [AVPlayerLayer playerLayerWithPlayer:self->player];
                self->playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;
                self->playerLayer.frame = CGRectMake(0, 0, pingmuKuan, pingmuGao);
                [self.bgView01.layer addSublayer:self->playerLayer];
                if (self.temBol04) {
                    [self->player play];
                }
                else {
                    [self->player pause];
                }
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(palMedioEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self->player.currentItem];
            }
        }];
        [download resume];
    }
}



- (void)palMedioEnd:(NSNotification *)notification{
    [player seekToTime:CMTimeMake(0, 1)];
    [player play];
}

-(void)backEvent{
    [player pause];
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)showOneView2
{
    if (self.medioIdexInte>= self.datArray.count) {
        self.medioIdexInte = 0;
    }if (self.medioIdexInte <0) {
        self.medioIdexInte = 0;
    }
    if (self.bgView02) {
        [self.bgView02 removeFromSuperview];
    }
    self.bgView02 = [[UIView alloc] initWithFrame:CGRectMake(0, pingmuGao, pingmuKuan, pingmuGao)];
    self.bgView02.backgroundColor = [UIColor clearColor];
    [self.scrollView insertSubview:self.bgView02 atIndex:0];
    [self.bgView02 addSubview:self.bgImageView04];
    self.bgView01 = [[UIView alloc] initWithFrame:self.bgView02.bounds];
    self.bgView01.backgroundColor = [UIColor clearColor];
    [self.bgView02 addSubview:self.bgView01];
    [self.bgView02 addSubview:self.bgImageView03];
    [self.bgView02 addSubview:self.shanliaoBtn];
    if (!self.bgImageView01) {
        self.bgImageView01 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, pingmuKuan, pingmuGao)];
        self.bgImageView01.backgroundColor = UIColor.clearColor;
        self.bgImageView01.contentMode =  UIViewContentModeScaleAspectFill;
        self.bgImageView01.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        self.bgImageView01.clipsToBounds  = YES;
        [self.scrollView addSubview:self.bgImageView01];
    }if (self.medioIdexInte>0 && self.medioIdexInte<self.datArray.count) {
        [self.bgImageView01 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?x-oss-process=image/resize,w_750",self.datArray[self.medioIdexInte-1][@"image"]]] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
    }
    if (!self.bgImageView02) {
        self.bgImageView02 = [[UIImageView alloc]initWithFrame:CGRectMake(0, pingmuGao*2, pingmuKuan, pingmuGao)];
        self.bgImageView02.backgroundColor = UIColor.clearColor;
        self.bgImageView02.contentMode =  UIViewContentModeScaleAspectFill;
        self.bgImageView02.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        self.bgImageView02.clipsToBounds  = YES;
        [self.scrollView addSubview:self.bgImageView02];
    }if (self.medioIdexInte>=0 && self.medioIdexInte+1<self.datArray.count) {
        [self.bgImageView02 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?x-oss-process=image/resize,w_750",self.datArray[self.medioIdexInte+1][@"image"]]] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
    }
    [_bgImageView04 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?x-oss-process=image/resize,w_750",self.datArray[self.medioIdexInte][@"image"]]] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    }];
    
    [self bofangshipingEventClick];
    [self showOneView1];
}

-(void)showOneView1
{
    _bgImageView03.sd_layout.leftSpaceToView(self.bgView02, 0).rightSpaceToView(self.bgView02, 0).bottomSpaceToView(self.bgView02, 0).heightIs(iOS_H(148));
    _shanliaoBtn.sd_layout.widthIs(iOS_frame_width(280)).heightIs(iOS_frame_width(120)).bottomSpaceToView(self.bgView02, iOS_frame_height(60)).centerXEqualToView(self.bgView02);
}

-(void)showOneView0
{
    UITapGestureRecognizer *singleFingerTap =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(selfViewClick:)];
    [self.view addGestureRecognizer:singleFingerTap];
    
    [self.view addSubview:self.fanhuiBtn];
    [self.view addSubview:self.gengduoBtn];
    [self.view addSubview:self.xqMedoImageViee];
    _xqMedoImageViee.hidden = YES;
    
    CGSize referenceSize = UIScreen.mainScreen.bounds.size;
    [self.scrollView setContentOffset:CGPointMake(0, referenceSize.height+zhuangtaiGao) animated:NO];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self showOneView2];
    
    _fanhuiBtn.sd_layout.topSpaceToView(self.view, zhuangtaiGao).leftSpaceToView(self.view, iOS_frame_width(0)).widthIs(iOS_frame_width(120)).heightIs(iOS_frame_width(120));
    _gengduoBtn.sd_layout.topSpaceToView(self.view, zhuangtaiGao).rightSpaceToView(self.view, iOS_frame_width(0)).widthIs(iOS_frame_width(120)).heightIs(iOS_frame_width(120));
    _xqMedoImageViee.sd_layout.centerXEqualToView(self.view).centerYEqualToView(self.view).widthIs(iOS_frame_height(180)).heightIs(iOS_frame_height(180));
    
    
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView
                  willDecelerate:(BOOL)decelerate {
    if (decelerate == NO) {
        if (self.temInter02 == 1 && self.temInter01 == 1) {
            [self scrollViewDidEndScrolling];
        }else{
            [XTXGongView showTipMsg:@"没有更多了"];
            self.temInter02 = self.temInter01 = 1;
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGSize galvanizeextortionist = UIScreen.mainScreen.bounds.size;
    if (scrollView.contentOffset.y <= pingmuGao) {
        if (self.medioIdexInte == 0) {
            scrollView.contentOffset = CGPointMake(0, galvanizeextortionist.height);
            self.temInter02 = 0;
        }
        if (self.temInter01 == 0) {
            scrollView.contentOffset = CGPointMake(0, galvanizeextortionist.height);
        }
    }
    if (scrollView.contentOffset.y > pingmuGao) {
        if (self.temInter02 == 0) {
            scrollView.contentOffset = CGPointMake(0, galvanizeextortionist.height);
        }
        if (self.medioIdexInte == self.datArray.count-1) {
            scrollView.contentOffset = CGPointMake(0, galvanizeextortionist.height);
            self.temInter01 = 0;
        }
    }
    if (self.temBol01) {
        self.temInter02 = self.temInter01 = 1;
        self.temBol01 = NO;
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.tepFlot1 = scrollView.contentOffset.y;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.pianyiY = scrollView.contentOffset.y;
    if (self.temInter02 == 1  && self.temInter01 == 1) {
        [self scrollViewDidEndScrolling];
    }else{
        [XTXGongView showTipMsg:@"没有更多了"];
        self.temInter02 = self.temInter01 = 1;
    }
}



#pragma mark - Private

- (void)scrollViewDidEndScrolling {
    if(self.tepFlot1 == self.scrollView.contentOffset.y){
        return;
    }
    NSString *fecklesshemorrhage = @"";
    if (self.pianyiY - self.tepFlot1 >0) {
        fecklesshemorrhage = @"up";
    }else{
        fecklesshemorrhage = @"dnow";
    }
    if ([fecklesshemorrhage isEqualToString:@"up"]) {
        if (self.medioIdexInte == self.datArray.count-1) {
            return;
        }
        self.medioIdexInte ++;
        if (self.datArray.count - self.medioIdexInte <= 3) {
            if (self.temBol02) {
                [self huoquyonghushipingxinxiClick];
                self.temBol02 = NO;
            }
            if (self.type != typeTwo) {
                if (self.huidiaoBloo0) {
                    self.huidiaoBloo0(@"2");
                }
            }
        }
    }if ([fecklesshemorrhage isEqualToString:@"dnow"]){
        if (self.medioIdexInte == 0) {
            return;
        }
        self.medioIdexInte --;
    }
    CGSize referenceSize = UIScreen.mainScreen.bounds.size;
    [self.scrollView setContentOffset:CGPointMake(0, referenceSize.height) animated:NO];
    if (self.medioIdexInte<0) {
        self.medioIdexInte = 0;
    }
    [self huoquyonghuxinxiClick:self.datArray[self.medioIdexInte][@"id"] withPush:NO];
    self.temInter02 = self.temInter01 = 1;
    [self showOneView2];
}



- (void)huoquyonghushipingxinxiClick
{
    if (self.type != typeTwo) {
        return;
    }
    self.pagInte++;
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"pack"] = APPLink;
    canshuMutDict[@"page"] = [NSString stringWithFormat:@"%ld",self.pagInte];
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    WeakSelf
    [XTXNetworking networkinggetxiucanglistdewangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            NSArray *newAr = dict[@"info"];
            if (newAr.count>0) {
                [weakSelf.datArray addObjectsFromArray:dict[@"info"]];
                self.temBol02 = YES;
            }
            
        }
    }];
}



- (void)selfViewClick:(UITapGestureRecognizer *)recognizer {
    if(player.rate == 1.0)
    {
        [player pause];
        self.temBol04 = NO;
        _xqMedoImageViee.hidden = NO;
    }else{
        [player play];
        self.temBol04 = YES;
        _xqMedoImageViee.hidden = YES;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
    });
    if (self.temBol05) {
        self.temBol04 = YES;
        [player play];
    }
    else {
        self.temBol04 = NO;
        [player pause];
    }
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.temInter02 = 1;
    self.temInter01 = 1;
    self.temBol02 = YES;
    self.temBol01 = NO;
    self.temBol03 = YES;
    self.temBol04 = YES;
    self.temBol05 = YES;
    self.scrollView = [UIScrollView new];
    self.scrollView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.scrollView];
    self.scrollView.frame = self.view.bounds;
    self.scrollView.contentSize = CGSizeMake(pingmuKuan, pingmuGao * 3);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    [self showOneView0];
    self.temBol01 = YES;
    [self huoquyonghuxinxiClick:self.datArray[self.medioIdexInte][@"id"] withPush:NO];
}



-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [player pause];
    if (self.temBol04) {
        self.temBol05 = YES;
    }
    else {
        self.temBol05 = NO;
    }
    self.temBol04 = NO;
}


@end
